
$(document).ready(function () {
    dialogDocSubmission.initDialog();

    $('.btn-submit-doc').click(function () {
        dialogDocSubmission.resetDialog();
        dialogDocSubmission.phaseId = $(this).parents('tr').data("phaseId");
        dialogDocSubmission.showDialog();
    });
});

var dialogDocSubmission = {
    phaseId: null,
    initDialog: function() {
        $('#input_file').change(function (e) {
            var file = e.currentTarget.files[0];
            if (file.size > 50e6) {
                UIkit.modal.alert("允许上传文件最大 50MB");
                dialogDocSubmission.resetDialog();
                return;
            }

            var fileInfoBox = $('#file_info');
            fileInfoBox.html(file.name + ' <em class="uk-text-muted">(' + prettifyFileSize(file.size) + ')</em>');
        });
        $('#btn_submit_doc').click(this.submitDocument);
    },
    resetDialog: function () {
        $('#form_submit_doc')[0].reset();
        $('#file_info').html(null);
        this.phaseId = null;
    },
    showDialog: function () {
        UIkit.modal('#dialog_doc_submission').show();
    },
    hideDialog: function () {
        UIkit.modal('#dialog_doc_submission').hide();
    },
    submitDocument: function () {
        var file = $('#input_file')[0].files[0];
        if (file == null) {
            UIkit.modal.alert('请先选择文件');
            return;
        }

        dialogDocSubmission.blockingModal = UIkit.modal.blockUI('正在上传，请耐心等候');
        var form = new FormData($('#form_submit_doc')[0]);
        $.ajax({
            url: '/api/studentDoc/upload/' + dialogDocSubmission.phaseId,
            data: form,
            type: 'POST',
            processData:false,
            contentType:false
        })
            .done(function (data) {
                location.reload();
            })
            .fail(function () {
                dialogDocSubmission.blockingModal.hide();
                UIkit.modal.alert('出现错误');
            })
    }

};

function prettifyFileSize(sizeByte) {
    if (isNaN(parseInt(sizeByte)))
        return NaN;

    if (sizeByte > 1e9) {
        return (sizeByte / 1e9).toFixed(1).replace('.0', '') + ' GB';
    }
    if (sizeByte > 1e6) {
        return (sizeByte / 1e6).toFixed(1).replace('.0', '') + ' MB';
    }
    if (sizeByte > 1e3) {
        return (sizeByte / 1e3).toFixed(1).replace('.0', '') + ' KB';
    }
    return sizeByte + '字节';
}